/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.esdc.librarysystem.web;

import com.esdc.librarysystem.exception.NotExistException;
import com.esdc.librarysystem.exception.HasOutstandingLoan;
import com.esdc.librarysystem.exception.OnReservedException;
import com.esdc.librarysystem.manager.CollectionManagerRemote;
import com.esdc.librarysystem.manager.LoanManagerRemote;
import com.esdc.librarysystem.manager.MemberManagerRemote;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author shou1dwe
 */
public class LibraryServlet extends HttpServlet {

    @EJB
    private LoanManagerRemote loanManager;
    @EJB
    private MemberManagerRemote memberManager;
    @EJB
    private CollectionManagerRemote collectionManager;

    String pageRedirect="";

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        RequestDispatcher dispatcher;
        ServletContext servletContext = getServletContext();
        String page = request.getPathInfo();
        System.out.println(page);
        pageRedirect = "";
        try {
            if (page.length() > 1) {
                String[] pathParts = page.split("/");
                page = pathParts[pathParts.length-1];
            }
            if(page.equals("Logout")){
                if(request.getSession()!=null){
                    request.getSession().removeAttribute("id");
                    pageRedirect = "Index";
                }
            } else if (page.equals("") || page.equals("/") || page.equals("Index")) {
                if (request.getSession()!=null && request.getSession().getAttribute("id") != null) {
                    pageRedirect = "Status";
                } else {
                    pageRedirect = "Index";
                }
            } else if (page.toLowerCase().equals("status")) {
                boolean verified = false;
                long memberId = -1;

                if (request.getSession() != null && request.getSession().getAttribute("id") != null) {
                    memberId = (Long) request.getSession().getAttribute("id");
                    verified = true;
                } else {
                    memberId = Long.parseLong(request.getParameter("memberId"));
                    String password = request.getParameter("password");
                    if(memberManager.verify(memberId, password)){
                        verified = true;
                    }
                    initiateMemberSession(memberId, request);
                }

                if (verified) {
                    if(request.getParameterValues("loan")!=null && request.getParameterValues("loan").length >0){
                        renewLoans(request, memberId);
                    }
                    if(request.getParameterValues("reservation")!=null && request.getParameterValues("reservation").length >0){
                        deleteReservations(request);
                    }
                    if(request.getParameterValues("result")!=null && request.getParameterValues("result").length >0){
                        addReservations(request, memberId);
                    }

                    ArrayList loans = (ArrayList) loanManager.returnLoans(memberId);
                    ArrayList reservations = (ArrayList) loanManager.returnReservations(memberId);
                    request.setAttribute("loans", loans);
                    request.setAttribute("reservations", reservations);
                    pageRedirect = "Status";
                } else {
                    request.setAttribute("error", "Invalid member id or password");
                    pageRedirect = "Error";
                }

            } else if (page.toLowerCase().equals("results")) {
                String keyword = request.getParameter("keyword");
                if (keyword == null || keyword.equals("")) {
                    pageRedirect = "Status";
                } else {
                    String category = request.getParameter("category");
                    ArrayList results = null;
                    if (category != null && category.equals("title")) {
                        results = (ArrayList) collectionManager.findBooksByTitle(keyword);
                    } else if( category != null && category.equals("author")){
                        results = (ArrayList) collectionManager.findBooksByAuthor(keyword);
                    }
                    request.setAttribute("results", results);

                    pageRedirect = "Results";
                }
            } else {
                pageRedirect = "Error";
            }
        } catch (NotExistException ex) {
            Logger.getLogger(LibraryServlet.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", ex.getMessage());
            pageRedirect = "Error";
        } catch (OnReservedException ex) {
            Logger.getLogger(LibraryServlet.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", ex.getMessage());
            pageRedirect = "Error";
        } catch (HasOutstandingLoan ex) {
            Logger.getLogger(LibraryServlet.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", ex.getMessage());
            pageRedirect = "Error";
        } catch (Exception e) {
            log("Exception in TLSServlet.processRequest()");
            print(e.getMessage());
            request.setAttribute("error", e.getMessage());
            pageRedirect = "Error";
        }
        dispatcher = servletContext.getNamedDispatcher(pageRedirect);
        if (dispatcher == null) {
            dispatcher = servletContext.getNamedDispatcher("Error");
        }
        dispatcher.forward(request, response);

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void print(String s) {
        System.out.println(s);
    }

    private void initiateMemberSession(long memberId, HttpServletRequest request) {
        HttpSession session = request.getSession(true);
        session.setAttribute("id", memberId);
    }

    private boolean renewLoans(HttpServletRequest request, Long memberId) throws NotExistException, OnReservedException, HasOutstandingLoan {
        String[] renewArray = request.getParameterValues("loan");
        if(renewArray.length<1) return true;
        List<Long> loanIdList = new ArrayList<Long>();
        for(String id : renewArray){
            loanIdList.add(Long.parseLong(id));
        }

        loanManager.renewLoanRestricted(loanIdList.toArray(new Long[loanIdList.size()]), memberId);
        
        return true;
    }

    private boolean deleteReservations(HttpServletRequest request) throws NotExistException {
                String[] reservationArray = request.getParameterValues("reservation");
        if(reservationArray.length<1) return true;
        List<Long> reservationIdList = new ArrayList<Long>();
        for(String id : reservationArray){
            reservationIdList.add(Long.parseLong(id));
        }

        loanManager.deleteReservations(reservationIdList.toArray(new Long[reservationIdList.size()]));
        
        return true;
    }

    private boolean addReservations(HttpServletRequest request, Long memberId) throws NotExistException {
        String[] resultArray = request.getParameterValues("result");
        if(resultArray.length<1) return true;
        List<Long> reservationIdList = new ArrayList<Long>();
        for(String id : resultArray){
            reservationIdList.add(Long.parseLong(id));
        }

        loanManager.newReservation(reservationIdList.toArray(new Long[reservationIdList.size()]), memberId);
        
        return true;
    }
}
